<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="file" id="fileInput">
  <button id="uploadBtn">上传</button>
  <button id="downloadBtn">下载</button>
  <script>
    // JavaScript 文件
    let jsonData;

    // 上传 JSON 文件并解析数据
    document.getElementById('fileInput').addEventListener('change', (event) => {
      const file = event.target.files[0];

      const reader = new FileReader();
      reader.readAsText(file);

      reader.onload = () => {
        try {
          jsonData = JSON.parse(reader.result);
          console.log(jsonData);
          // 处理其中的数据
          for (const iterator of jsonData.features) {
            // debugger
            delete iterator.type
            if(!iterator?.geometry?.type) return
            const geometry = iterator.geometry
            if(geometry.type === 'Point'){  // 点
              geometry.coordinates = point3to2(geometry.coordinates)
            }else if(geometry.type === 'LineString'){ // 线
              geometry.coordinates = linePolygon3to2(geometry.coordinates)
            }else if(geometry.type === 'MultiLineString'){  // 多线
              const multiCoordinates = geometry.coordinates
              const ultimatelyCoordinates = []
              for (const coordinates of multiCoordinates) {
                ultimatelyCoordinates.push(linePolygon3to2(coordinates))
              }
              geometry.coordinates = ultimatelyCoordinates
            }else if(geometry.type === 'Polygon'){    // 面
              geometry.coordinates[0] = linePolygon3to2(geometry.coordinates[0])
            }else if(geometry.type === 'MultiPolygon'){   // 多面
              const multiCoordinates = geometry.coordinates
              const ultimatelyCoordinates = []
              for (const coordinates of multiCoordinates) {
                ultimatelyCoordinates.push([linePolygon3to2(coordinates[0])])
              }
              geometry.coordinates = ultimatelyCoordinates
            }
          }
        } catch (err) {
          console.error(err);
        }
      };

      reader.onerror = () => {
        console.error(reader.error);
      };
    });

    function point3to2(coordinate){
      return [Number(coordinate[0].toFixed(2)), Number(coordinate[1].toFixed(2))]
    }
    function linePolygon3to2(coordinates){
      const newCoordinates = []
      for (const coord of coordinates) {
        newCoordinates.push(point3to2(coord))
      }
      return newCoordinates
    }

    // 压缩 JSON 数据并下载文件
    document.getElementById('downloadBtn').addEventListener('click', () => {
      if (!jsonData) {
        console.error('请先上传 JSON 文件！');
        return;
      }

      // 将数据转换为 JSON 字符串
      let jsonString = JSON.stringify(jsonData);

      // 压缩 JSON 字符串并去除空格与换行符
      jsonString = jsonString.replace(/\s+/g, '');
      // console.log(jsonData)

      // 创建并下载 JSON 文件
      const downloadFile = (content, fileName, contentType) => {
        const a = document.createElement('a');
        const file = new Blob([content], { type: contentType });

        a.href = URL.createObjectURL(file);
        a.download = fileName;
        a.click();

        URL.revokeObjectURL(a.href);
      };

      downloadFile(jsonString, 'jxcad1.json', 'application/json');
      // exportJson(jsonData, 'jxcad.json')
    });

    function exportJson(data, filename) {
      if (!data) {
        alert('保存的数据为空')
        return
      }
      if (!filename) {
        filename = 'json.json'
      }
      if (typeof data === 'object') {
        data = JSON.stringify(data, undefined, 2)
      }
      const blob = new Blob([data], { type: 'text/json' })
      const e = document.createEvent('MouseEvents')
      const a = document.createElement('a')
    
      a.download = filename
      a.href = window.URL.createObjectURL(blob)
      a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
      e.initMouseEvent(
        'click',
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      )
      a.dispatchEvent(e)
    }

  </script>
</body>

</html>